package jjn.round1;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author Jjn
 * @since 2022-09-19 17:19
 */
public class LeetCode1636_FrequencySort {
    public int[] frequencySort(int[] nums) {
        // 1, 1, 2, 2, 2, 3
        Map<Integer, Integer> countMap = new TreeMap<>();
        for (int num : nums) {
            Integer count = countMap.getOrDefault(num, 0);
            count++;
            countMap.put(num, count);
        }
        List<Integer> list = new ArrayList<>();
        for (int num : nums) {
            list.add(num);
        }
        list.sort((i, j) -> {
            int count1 = countMap.get(i);
            int count2 = countMap.get(j);
            return count1 != count2 ? count1 - count2 : j - i;
        });
        int[] result = new int[nums.length];
        for (int i = 0; i < nums.length; i++) {
            result[i] = list.get(i);
        }
        return result;
    }
}
